﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;

public class CustomerExceptionFilter : ExceptionFilterAttribute
{
    private readonly ILogger<CustomerExceptionFilter> _logger;

    public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger)
    {
        _logger = logger;
    }

    public override void OnException(ExceptionContext context)
    {
        Exception ex = context.Exception;
        HttpRequest request = context.HttpContext.Request;
        string requestUrl = $"{request.Scheme}://{request.Host.Value}{request.Path}";
        string errorMsg = $"error:{ex.GetBaseException().Message};requesturl:{requestUrl}";
        _logger.LogError(errorMsg);
        var result = new { code = 0, msg = errorMsg, data = "" };
        string json = JsonConvert.SerializeObject(result);
        context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
        context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
        context.HttpContext.Response.WriteAsync(json);
        context.ExceptionHandled = true;
    }
}